package com.shungen.apicloud.utils;

import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

public class UrlUtils {

    /**
     * 从完整的URL中提取URI部分
     *
     * @param urlString 完整的URL地址
     * @return 提取的URI部分
     * @throws URISyntaxException 当URL格式不正确时抛出异常
     */
    public static String extractUri(String urlString) throws URISyntaxException {
        // 检查URL是否以协议开头，如果没有则默认添加 "http://"
        if (!urlString.matches("^[a-zA-Z][a-zA-Z0-9+.-]*:.*")) {
            urlString = "http://" + urlString;
        }

        try {
            // 尝试将字符串解析为URL
            URL url = new URL(urlString);
            URI uri = url.toURI();
            return uri.getPath() + (uri.getQuery() != null ? "?" + uri.getQuery() : "")
                    + (uri.getFragment() != null ? "#" + uri.getFragment() : "");
        } catch (Exception e) {
            // 如果URL无法解析，直接用URI类解析
            URI uri = new URI(urlString);
            return uri.getPath() + (uri.getQuery() != null ? "?" + uri.getQuery() : "")
                    + (uri.getFragment() != null ? "#" + uri.getFragment() : "");
        }
    }

    public static void main(String[] args) {
        try {
            System.out.println(extractUri("http://localhost:8080/test/path?query=1#section")); // /test/path?query=1#section
            System.out.println(extractUri("https://www.example.com/test/path")); // /test/path
            System.out.println(extractUri("ftp://example.com/resource")); // /resource
            System.out.println(extractUri("localhost:3306/test/1")); // /test/1
            System.out.println(extractUri("example.com/test/1")); // /test/1
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
}
